<template>
	<view class="container">
		<view class="header">
			<button class="create-btn" @click="navigateTo('/pages/excel/create')">创建Excel表</button>
		</view>
		
		<view class="content">
			<view v-if="excelList.length === 0" class="empty-state">
				<text class="empty-text">暂无Excel表，点击上方按钮创建</text>
			</view>
			
			<view v-else class="excel-list">
				<view v-for="(item, index) in excelList" :key="index" class="excel-item">
					<view class="excel-info">
						<text class="excel-name">{{item.name}}</text>
						<text class="excel-date">创建于 {{item.createTime}}</text>
					</view>
					
					<view class="excel-actions">
						<text class="action-btn" @click="viewExcel(item)">查看</text>
						<text class="action-btn copy" @click="copyExcelData(item)">复制</text>
						<text class="action-btn download" @click="downloadExcel(item)">下载</text>
						<text class="action-btn clear" @click="clearExcel(item)">清空</text>
						<text class="action-btn delete" @click="deleteExcel(item)">删除</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
	data() {
		return {
			excelList: []
		}
	},
	onShow() {
		this.loadExcelList()
	},
	methods: {
		navigateTo(url) {
			uni.navigateTo({
				url
			})
		},
		loadExcelList() {
			// TODO: 从本地存储加载Excel列表
			const list = uni.getStorageSync('excelList') || []
			this.excelList = list
		},
		viewExcel(item) {
			uni.navigateTo({
				url: '/pages/excel/view?id=' + item.id
			})
		},
		downloadExcel(item) {
			uni.showLoading({ title: '正在生成文件...' });

			try {
				// #ifdef H5
				// H5环境下载
				const excelList = uni.getStorageSync('excelList') || [];
				const excelData = excelList.find(i => i.id === item.id);
				if (!excelData) {
					uni.hideLoading();
					uni.showToast({ title: '未找到表格数据', icon: 'none' });
					return;
				}
				
				const worksheet = XLSX.utils.json_to_sheet(excelData.data);
				const workbook = XLSX.utils.book_new();
				XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
				const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
				const blob = new Blob([excelBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
				const link = document.createElement("a");
				link.href = URL.createObjectURL(blob);
				link.download = `${excelData.name}.xlsx`;
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
				
				uni.hideLoading();
				uni.showToast({
					title: '文件下载成功',
					icon: 'success'
				});
				// #endif

				// #ifdef APP-PLUS
				// APP环境下载
				const excelList_app = uni.getStorageSync('excelList') || [];
				const excelData_app = excelList_app.find(i => i.id === item.id);
				
				if (!excelData_app) {
					uni.hideLoading();
					uni.showToast({ title: '未找到表格数据', icon: 'none' });
					return;
				}
				
				// 准备数据
				let dataToExport = excelData_app.data || [];
				if (dataToExport.length === 0) {
					dataToExport = [{ '列1': '示例数据1', '列2': '示例数据2' }];
				}
				
				// 生成Excel文件
				const worksheet_app = XLSX.utils.json_to_sheet(dataToExport);
				const workbook_app = XLSX.utils.book_new();
				XLSX.utils.book_append_sheet(workbook_app, worksheet_app, "Sheet1");
				const excelBuffer_app = XLSX.write(workbook_app, { bookType: "xlsx", type: "array" });
				
				// 转换为Uint8Array
				let uint8Array;
				if (excelBuffer_app instanceof Uint8Array) {
					uint8Array = excelBuffer_app;
				} else if (excelBuffer_app instanceof ArrayBuffer) {
					uint8Array = new Uint8Array(excelBuffer_app);
				} else {
					uint8Array = new Uint8Array(excelBuffer_app);
				}
				
				// 保存文件
				this.saveFileToDevice(uint8Array, excelData_app.name + '.xlsx');
				// #endif

			} catch(e) {
				uni.hideLoading();
				uni.showModal({
					title: '下载失败',
					content: `生成文件时发生错误: ${e.message}`,
					showCancel: false
				});
			}
		},
		deleteExcel(item) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除该Excel表吗？',
				success: (res) => {
					if (res.confirm) {
						try {
							// 获取当前Excel列表
							const excelList = uni.getStorageSync('excelList') || [];
							// 过滤掉要删除的表格
							const newList = excelList.filter(i => i.id !== item.id);
							
							// 保存到本地存储
							uni.setStorageSync('excelList', newList);
							
							// 更新页面显示数据
							this.excelList = newList;
							
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						} catch (error) {
							console.error('删除表格失败:', error);
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 保存文件到设备
		saveFileToDevice(uint8Array, fileName) {
			try {
				// 转换为base64
				let binary = '';
				for (let i = 0; i < uint8Array.length; i++) {
					binary += String.fromCharCode(uint8Array[i]);
				}
				const base64Data = btoa(binary);
				
				// 使用uni-app文件系统API
				const fs = uni.getFileSystemManager();
				
				// 构建文件路径
				const context = plus.android.runtimeMainActivity().getApplicationContext();
				const File = plus.android.importClass("java.io.File");
				const filesDir = plus.android.invoke(context, "getFilesDir");
				const saveDir = new File(filesDir, "Downloads");
				
				if (!plus.android.invoke(saveDir, "exists")) {
					plus.android.invoke(saveDir, "mkdirs");
				}
				
				const file = new File(saveDir, fileName);
				const fullPath = plus.android.invoke(file, "getAbsolutePath");
				
				// 写入文件
				fs.writeFile({
					filePath: fullPath,
					data: base64Data,
					encoding: 'base64',
					success: (res) => {
						uni.hideLoading();
						uni.showModal({
							title: '下载成功',
							content: `文件已保存至应用目录\n文件名: ${fileName}\n\n是否要分享此文件？`,
							confirmText: '分享',
							cancelText: '稍后',
							success: (modalRes) => {
								if (modalRes.confirm) {
									this.shareFile(fullPath, fileName);
								}
							}
						});
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showModal({
							title: '保存失败',
							content: `无法保存文件: ${err.errMsg}`,
							showCancel: false
						});
					}
				});
				
			} catch (error) {
				uni.hideLoading();
				uni.showModal({
					title: '保存失败',
					content: `处理文件时发生错误: ${error.message}`,
					showCancel: false
				});
			}
		},
		
		// 询问是否分享文件
		askToShareFile(filePath, fileName) {
			uni.showModal({
				title: '文件操作',
				content: `是否要分享此Excel文件？\n文件名：${fileName}\n\n分享后可以：\n• 发送给其他人\n• 在其他应用中打开\n• 保存到其他位置`,
				confirmText: '分享文件',
				cancelText: '稍后再说',
				success: (res) => {
					if (res.confirm) {
						this.shareFile(filePath, fileName);
					}
				}
			});
		},
		
		// 分享文件
		shareFile(filePath, fileName) {
			try {
				const context = plus.android.runtimeMainActivity().getApplicationContext();
				const Intent = plus.android.importClass("android.content.Intent");
				const Uri = plus.android.importClass("android.net.Uri");
				const File = plus.android.importClass("java.io.File");
				const FileProvider = plus.android.importClass("androidx.core.content.FileProvider");
				
				// 创建文件对象
				const file = new File(filePath);
				
				// 使用FileProvider获取Uri（适配Android 7.0+）
				let fileUri = null;
				try {
					// 尝试使用FileProvider
					const authority = plus.runtime.appid + ".fileprovider";
					fileUri = plus.android.invoke(FileProvider, "getUriForFile", context, authority, file);
				} catch (providerError) {
					console.log('FileProvider失败，使用直接Uri:', providerError.message);
					// 备选：直接使用文件Uri
					fileUri = Uri.fromFile(file);
				}
				
				// 创建分享Intent
				const shareIntent = new Intent(Intent.ACTION_SEND);
				plus.android.invoke(shareIntent, "setType", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
				plus.android.invoke(shareIntent, "putExtra", Intent.EXTRA_STREAM, fileUri);
				plus.android.invoke(shareIntent, "putExtra", Intent.EXTRA_SUBJECT, fileName);
				plus.android.invoke(shareIntent, "putExtra", Intent.EXTRA_TEXT, "分享Excel文件：" + fileName);
				plus.android.invoke(shareIntent, "addFlags", Intent.FLAG_GRANT_READ_URI_PERMISSION);
				
				// 创建选择器
				const chooserIntent = Intent.createChooser(shareIntent, "选择应用打开Excel文件");
				plus.android.invoke(chooserIntent, "addFlags", Intent.FLAG_ACTIVITY_NEW_TASK);
				
				// 启动分享
				context.startActivity(chooserIntent);
				
				uni.showToast({
					title: '正在打开分享选择器...',
					icon: 'none'
				});
				
			} catch (shareError) {
				console.error('分享文件失败:', shareError);
				
				// 分享失败，尝试直接打开文件
				this.openFileWithDefault(filePath, fileName);
			}
		},
		
		// 尝试用默认应用打开文件
		openFileWithDefault(filePath, fileName) {
			try {
				const context = plus.android.runtimeMainActivity().getApplicationContext();
				const Intent = plus.android.importClass("android.content.Intent");
				const Uri = plus.android.importClass("android.net.Uri");
				const File = plus.android.importClass("java.io.File");
				
				const file = new File(filePath);
				const fileUri = Uri.fromFile(file);
				
				const openIntent = new Intent(Intent.ACTION_VIEW);
				plus.android.invoke(openIntent, "setDataAndType", fileUri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
				plus.android.invoke(openIntent, "addFlags", Intent.FLAG_ACTIVITY_NEW_TASK);
				plus.android.invoke(openIntent, "addFlags", Intent.FLAG_GRANT_READ_URI_PERMISSION);
				
				context.startActivity(openIntent);
				
			} catch (openError) {
				console.error('打开文件失败:', openError);
				uni.showModal({
					title: '提示',
					content: `无法自动打开文件\n\n请手动在文件管理器中查找：\n文件名：${fileName}\n\n或安装Excel/WPS等应用来打开.xlsx文件`,
					showCancel: false
				});
			}
		},
		
		// 复制Excel数据到剪贴板
		copyExcelData(item) {
			try {
				// 获取Excel数据
				const excelList = uni.getStorageSync('excelList') || [];
				const excelData = excelList.find(i => i.id === item.id);
				
				if (!excelData || !excelData.data || excelData.data.length === 0) {
					uni.showToast({
						title: '没有数据可复制',
						icon: 'none'
					});
					return;
				}
				
				console.log('开始转换Excel数据为剪贴板格式');
				
				// 转换数据为TSV格式（Tab-Separated Values）
				const data = excelData.data;
				let tsvContent = '';
				
				// 处理表头
				if (data.length > 0) {
					const headers = Object.keys(data[0]);
					tsvContent += headers.join('\t') + '\n';
					
					// 处理数据行
					data.forEach(row => {
						const values = headers.map(header => {
							let value = row[header] || '';
							// 处理特殊字符，确保复制格式正确
							if (typeof value === 'string') {
								// 如果包含制表符、换行符或引号，需要特殊处理
								if (value.includes('\t') || value.includes('\n') || value.includes('"')) {
									value = '"' + value.replace(/"/g, '""') + '"';
								}
							}
							return value;
						});
						tsvContent += values.join('\t') + '\n';
					});
				}
				
				console.log('数据转换完成，准备复制到剪贴板');
				console.log('数据行数:', data.length);
				console.log('数据列数:', data.length > 0 ? Object.keys(data[0]).length : 0);
				
				// 复制到剪贴板
				uni.setClipboardData({
					data: tsvContent,
					success: () => {
						console.log('复制成功');
						
						// 显示成功提示
						uni.showModal({
							title: '复制成功',
							content: `Excel数据已复制到剪贴板！\n\n包含数据：\n• 数据行数：${data.length} 行\n• 数据列数：${data.length > 0 ? Object.keys(data[0]).length : 0} 列\n\n使用方法：\n1. 打开Excel、WPS等表格应用\n2. 创建新表格或打开现有表格\n3. 选择目标单元格（如A1）\n4. 粘贴（Ctrl+V）`,
							showCancel: false,
							confirmText: '知道了'
						});
					},
					fail: (err) => {
						console.error('复制失败:', err);
						uni.showModal({
							title: '复制失败',
							content: `无法复制到剪贴板\n错误信息：${err.errMsg || '未知错误'}\n\n可能的原因：\n• 系统权限限制\n• 剪贴板被占用\n• 数据过大`,
							showCancel: false
						});
					}
				});
				
			} catch (error) {
				console.error('复制数据处理失败:', error);
				uni.showToast({
					title: '数据处理失败',
					icon: 'none'
				});
			}
		},
		
		// 清空Excel表内容
		clearExcel(item) {
			uni.showModal({
				title: '确认清空',
				content: '确定要清空该Excel表的所有数据吗？表格名称和结构将保留，但所有数据行将被删除。',
				success: (res) => {
					if (res.confirm) {
						try {
							// 获取当前Excel列表
							const excelList = uni.getStorageSync('excelList') || [];
							const targetIndex = excelList.findIndex(i => i.id === item.id);
							
							if (targetIndex !== -1) {
								// 清空数据但保留表格结构
								excelList[targetIndex].data = [];
								
								// 保存到本地存储
								uni.setStorageSync('excelList', excelList);
								
								// 更新页面显示
								this.excelList = excelList;
								
								uni.showToast({
									title: '清空成功',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: '未找到该表格',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('清空表格失败:', error);
							uni.showToast({
								title: '清空失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
	}
}
</script>

<style>
.container {
	padding: 20px;
	min-height: 100vh;
	background-color: #f8f8f8;
}

.header {
	margin-bottom: 20px;
}

.create-btn {
	background-color: #007AFF;
	color: #fff;
	border-radius: 8px;
	font-size: 16px;
}

.empty-state {
	text-align: center;
	padding: 40px 0;
}

.empty-text {
	color: #999;
	font-size: 14px;
}

.excel-list {
	display: flex;
	flex-direction: column;
	gap: 15px;
}

.excel-item {
	background: #fff;
	border-radius: 12px;
	padding: 15px;
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.excel-info {
	flex: 1;
}

.excel-name {
	font-size: 16px;
	color: #333;
	font-weight: 500;
	margin-bottom: 5px;
	display: block;
}

.excel-date {
	font-size: 12px;
	color: #999;
}

.excel-actions {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
	margin-top: 5px;
	border-top: 1px solid #f0f0f0;
	padding-top: 10px;
}

.action-btn {
	font-size: 14px;
	color: #007AFF;
	padding: 5px 8px;
	border-radius: 4px;
	background-color: #f8f9fa;
	text-align: center;
	min-width: 50px;
}

.action-btn.delete {
	color: #FF3B30;
	background-color: #fff2f2;
}

.action-btn.copy {
	color: #FF9500;
	background-color: #fff8f0;
}

.action-btn.download {
	color: #34C759;
	background-color: #f0fdf4;
}

.action-btn.clear {
	color: #FF9500;
	background-color: #fff8f0;
}

.debug-btn {
	background-color: #007AFF;
	color: #fff;
	border-radius: 8px;
	font-size: 16px;
	margin-left: 10px;
}

.debug-btn.debug-on {
	background-color: #FF3B30;
}

.debug-btn.debug-off {
	background-color: #007AFF;
}
</style> 